package com.sunshuo.springsecuritydemo.controller;

import com.sunshuo.springsecuritydemo.dao.MenuDao;
import com.sunshuo.springsecuritydemo.pojo.Menu;
import com.sunshuo.springsecuritydemo.service.MenuService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AliasFor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

/**
 * @ClassName MenuController
 * @Description
 * @Author sunshuo
 * @Date 2021/11/7 19:13
 */
@Controller
@RequestMapping("/menu")
public class MenuController {

    private MenuService menuService;

    @Autowired
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }

    @PreAuthorize("hasRole('DIRECTOR')")
    @RequestMapping("/page")
    @ResponseBody
    public String page() {
        JSONObject result = new JSONObject();
        result.put("url", "/menu/menu.jsp");
        return result.toString();
    }

    @RequestMapping("/query_role_auth_tree")
    @ResponseBody
    public String queryAll(String roleId) {
        final List<Menu> menus = menuService.getAll();
        final List<String> codes = menuService.getAuthCodeByRoleNames(Arrays.asList(roleId));
        JSONArray results = new JSONArray();
        menus.forEach(menu -> {
            JSONObject data = new JSONObject();
            data.put("id", menu.getId());
            data.put("title", menu.getTitle());
            data.put("checked", codes.contains(menu.getAuthCode()));
            data.put("authCode", menu.getAuthCode());
            results.put(data);
        });
        return results.toString();
    }

}
